package com.tuu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuu.configBean.RedisUtil;
import com.tuu.constvar.Constants;
import com.tuu.mapper.JwtUserMapper;
import com.tuu.mapper.UserMapper;
import com.tuu.pojo.JwtClainsObject;
import com.tuu.pojo.JwtUser;
import com.tuu.pojo.User;
import com.tuu.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.PoolException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service  //implements UserService
public class UserServiceImpl2222Origin {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUserMapper jwtUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private MyUtils myUtils;
    @Value("${jwt.expiration}")
    String exp;
    @Value("${jwt.userVersionExpiration}")
    String userExp;
    @Value("${jwt.pVersionName}")
    String pVersionName;
    @Value("${jwt.userIdentifier}")
    String userIdent;
    @Value("${jwt.userIdentFakes}")
    String userIdentFakes;
    //@Override
    public Map<String,Object> login(Map deviceInfo,User user) throws Exception {
        Map<String,Object> map=new HashMap<>();
        User user1 =new User();
        user1.setName(user.getName());
        user1.setPass(user.getPass());
        System.out.println(user.getName()+"-----"+user.getPass());
        QueryWrapper qw = new QueryWrapper();
        qw.setEntity(user1);
        //qw.select("name","pass");//只查询age和name字段
        User b = userMapper.selectOne(qw);
        String token=null;
        if(b!=null){
            JwtClainsObject jco=new JwtClainsObject();
            String ipaddress=IPAdressUtils.getIpAddress((HttpServletRequest)ObjectThreadLocal.get());
            jco.setIp(ipaddress);
            System.out.println("地址"+ipaddress);
            jco.setRandomId(UUID.randomUUID().toString().replaceAll("-", ""));
            jco.setSubjectUid(b.getId());
            //5分钟 毫秒
            jco.setTtlMillis(Constants.JwtConst.EXPMILLIS.getTimee());
            jco.setUsername(user.getName());
            //jco.setBrowerName((String)deviceInfo.get("browser_name"));
            //jco.setSystemName((String)deviceInfo.get("system_name"));
            //jco.setBrowerVersion((String)deviceInfo.get("browser_version"));
            token=JWTUtils.createJWT(jco);
            try{
                redisUtil.set("uid"+b.getId()+"token",token,Long.parseLong(""+Constants.JwtConst.EXPMILLIS.getTimee()/1000L));
            }catch (Exception e){
                System.out.println("捕捉到redis错误。。。。");
                throw new PoolException("redis连接不行了");
            }
            //MyAesUtils.encrypt(b.getId(),"ppp");
            map.put("token",token);
            map.put("nickname",b.getName());
            //给uid加密
            map.put("bii",MyAesUtils.encrypt(b.getId(),Constants.JwtConst.AES16KEY.getValue()));
            System.out.println("正在返回cookies 在login页面");
            //清除request
            //GlobalMap.clear();
            ObjectThreadLocal.remove();
        }
        return map;
    }
    //@Override
    public Map<String,Object> login2(Map deviceInfo,JwtUser user) throws Exception {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> mapCookies=new HashMap<>();
        JwtUser user1 =new JwtUser();
        user1.setUsername(user.getUsername());
        //user1.setPass(user.getPassword());
        System.out.println(user.getUsername()+"-----"+user.getPassword());
        QueryWrapper qw = new QueryWrapper();
        qw.setEntity(user1);
        //qw.select("name","pass");//只查询age和name字段
        JwtUser b = jwtUserMapper.selectOne(qw);
        String token=null;
        if(b!=null){
            if(!passwordEncoder.matches(user.getPassword(),b.getPassword())){
                System.out.println("密码不匹配。。。");
                return null;
            }
            JwtClainsObject jco=new JwtClainsObject();
            jco.setRandomId(UUID.randomUUID().toString().replaceAll("-", ""));
            jco.setSubjectUid(b.getId());
            //5分钟 毫秒
            //jco.setTtlMillis(Constants.JwtConst.EXPMILLIS.getTimee());
            //jwt有效时间20分钟
            jco.setTtlMillis(Long.parseLong(exp));
            jco.setUsername(user.getUsername());
            token=jwtTokenUtil.generateToken2(jco);
            System.out.println("login2的token是"+token);
            try{
                //""+Constants.JwtConst.EXPMILLIS.getTimee()
                redisUtil.set("uid"+b.getId()+"token",token,Long.parseLong(exp)/1000L);
                redisUtil.set("uid"+b.getId()+"pVersion",(String)redisUtil.get(pVersionName),Long.parseLong(userExp)/1000L);
            }catch (Exception e){
                System.out.println("捕捉到redis错误。。。。");
                throw new PoolException("redis连接不行了");
            }
            //MyAesUtils.encrypt(b.getId(),"ppp");
            map.put("token",token);
            mapCookies.put("nickname",b.getUsername());
            mapCookies.put(userIdent,jco.getRandomId());
            String[] fakes=userIdentFakes.split(",");
            for(String f : fakes){
                mapCookies.put(f,myUtils.randomString(myUtils.GetRandomNum(5,46)));
            }
            map.put("cookies",mapCookies);
            //给uid加密
            //map.put("tmc",MyAesUtils.encrypt(b.getId(),Constants.JwtConst.AES16KEY.getValue()));
            //map.put("tmc",jco.getRandomId());
            System.out.println("正在返回cookies 在login页面");
            //清除request
            //GlobalMap.clear();
            //ObjectThreadLocal.remove();
        }
        return map;
    }
    //去掉地址 和 设备验证  之前的源码 login3
    public Map<String,Object> login3(Map deviceInfo,JwtUser user) throws Exception {
        Map<String,Object> map=new HashMap<>();
        JwtUser user1 =new JwtUser();
        user1.setUsername(user.getUsername());
        //user1.setPass(user.getPassword());
        System.out.println(user.getUsername()+"-----"+user.getPassword());
        QueryWrapper qw = new QueryWrapper();
        qw.setEntity(user1);
        //qw.select("name","pass");//只查询age和name字段
        JwtUser b = jwtUserMapper.selectOne(qw);
        String token=null;
        if(b!=null){
            if(!passwordEncoder.matches(user.getPassword(),b.getPassword())){
                System.out.println("密码不匹配。。。");
                return null;
            }
            JwtClainsObject jco=new JwtClainsObject();
            String ipaddress=IPAdressUtils.getIpAddress((HttpServletRequest)ObjectThreadLocal.get());
            jco.setIp(ipaddress);
            System.out.println("地址"+ipaddress);
            jco.setRandomId(UUID.randomUUID().toString().replaceAll("-", ""));
            jco.setSubjectUid(b.getId());
            //5分钟 毫秒
            jco.setTtlMillis(Constants.JwtConst.EXPMILLIS.getTimee());
            jco.setUsername(user.getUsername());
            //jco.setBrowerName((String)deviceInfo.get("browser_name"));
            //jco.setSystemName((String)deviceInfo.get("system_name"));
            //jco.setBrowerVersion((String)deviceInfo.get("browser_version"));
            token=jwtTokenUtil.generateToken2(jco);
            System.out.println("login2的token是"+token);
            try{
                //""+Constants.JwtConst.EXPMILLIS.getTimee()
                redisUtil.set("uid"+b.getId()+"token",token,Long.parseLong(exp)/1000L);
                redisUtil.set("uid"+b.getId()+"pVersion",(String)redisUtil.get(pVersionName),Long.parseLong(userExp)/1000L);
            }catch (Exception e){
                System.out.println("捕捉到redis错误。。。。");
                throw new PoolException("redis连接不行了");
            }
            //MyAesUtils.encrypt(b.getId(),"ppp");
            map.put("token",token);
            map.put("nickname",b.getUsername());
            //给uid加密
            map.put("bii",MyAesUtils.encrypt(b.getId(),Constants.JwtConst.AES16KEY.getValue()));
            System.out.println("正在返回cookies 在login页面");
            //清除request
            //GlobalMap.clear();
            ObjectThreadLocal.remove();
        }
        return map;
    }
    //@Override
    public void logout(String token, HttpServletRequest request) throws Exception{
        jwtTokenUtil.logoutJWT(token,request);
    }
}